package com.drinks.yiniang.io.service;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;

import com.drinks.yiniang.R;
import com.drinks.yiniang.io.api.MainApiIO;
import com.drinks.yiniang.utils.FileUtils;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.listener.OnDownloadListener;
import com.hansen.library.utils.LogUtils;
import com.hansen.library.utils.StringUtils;

import java.io.File;
import java.io.IOException;

/**
 * Created by han on 2019/4/1 0001.
 */

public class DownloadService extends Service {
    //下载完成
    private static final int DOWN_OK = 0x01;
    //下载失败
    private static final int DOWN_ERROR = 0x02;
    //下载中
    private static final int DOWN_UPDATE = 0x03;

    private NotificationManager notificationManager;
    private Notification.Builder builder;
    private Notification notification;

    //private RemoteViews contentView;

    private int mChannelId = 0x01;

    //apk名
    private String apkName;
    //下载地址
    private String mDownloadUrl;
    //最新版本号
    private String mVersionName;

    private int updateCount = 0;
    //更新步数， 大于2步更新一次
    private int down_step = 2;
    //总进度
    private long totals;
    //当前进度
    private long currents;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWN_OK:
                    installApk();
                    break;
                case DOWN_UPDATE:
                    if (notificationManager != null) { // 改变通知栏
                        int progress = (int) (currents * 1.0f / totals * 100);

                        builder.setProgress(100, progress, false);
                        builder.setContentText("下载进度: " + progress + "%");

                        notification = builder.build();

                        notificationManager.notify(1, notification);
                    }
                    break;
                case DOWN_ERROR:
                    builder.setAutoCancel(true);
                    builder.setContentText("下载失败");
                    notification = builder.build();

                    notificationManager.notify(1, notification);

                    stopSelf();
                    break;
                default:
                    break;
            }
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mDownloadUrl = intent.getStringExtra(Constants.KeyUrl);
        mVersionName = intent.getStringExtra(Constants.KeyName);

        if (!StringUtils.isHttp(mDownloadUrl)) {
            ToastUtils.showLong(getString(R.string.text_error_download_url));
            stopSelf();
        } else {
            createNotification();
            downloadFile();
        }

        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 方法描述：createNotification方法
     *
     * @param
     * @return
     * @see DownloadService
     */
    public void createNotification() {
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        builder = getNotifivationBuilder();
        builder.setSmallIcon(R.mipmap.app_logo)
                .setTicker("新消息")
                .setAutoCancel(false)
                .setWhen(System.currentTimeMillis())
                .setProgress(100, 0, false)
                .setContentText("下载进度: 0%");

        notification = builder.build();

        notificationManager.notify(1, notification);
    }

    private void downloadFile() {
        if(!judgeSDPermission()) {
            stopSelf();
            return;
        }

        ToastUtils.showLong(getString(R.string.text_downloading_in_notification));

        apkName = Constants.FileName + mVersionName + ".apk";

        /**
         * 下载文件方法
         * @param url 下载文件的url
         * @param target 下载文件的路径
         */
        MainApiIO.getInstance().postDownLoad(mDownloadUrl, Constants.RootApkPath, apkName, new OnDownloadListener() {
            @Override
            public void onDownloadSuccess() {
                Message message = new Message();
                message.what = DOWN_OK;

                handler.sendMessage(message);
            }

            @Override
            public void onDownloading(long total, long current) {
                if (current == 0 || (current * 100) / total >= updateCount) {
                    updateCount += down_step;

                    totals = total;
                    currents = current;

                    handler.sendEmptyMessage(DOWN_UPDATE);
                }
            }

            @Override
            public void onDownloadFailed(Exception e) {
                handler.sendEmptyMessage(DOWN_ERROR);

                LogUtils.e("e===" + e.toString());
            }
        });
    }

    private boolean judgeSDPermission() {
        if (!FileUtils.hasSdcard()) {//没有sd卡
            LogUtils.e("没有插入SD卡");
            return false;
        }

        if (!FileUtils.checkExternalStorageCanWrite()) {//没有SD卡读取权限
            ToastUtils.showLong("已禁用读写手机存储权限，请进入手机“设置-权限管理”页面手动授权");
            return false;
        }

        if (FileUtils.getSDFreeSize() < 60) {//sd卡剩余空间不足
            ToastUtils.showLong("手机剩余空间不足");
            return false;
        }

        if (!FileUtils.isExistDirOrMkdirs(Constants.RootApkPath)) {//创建文件失败
            LogUtils.e("创建文件失败");
            return false;
        }

        return true;
    }

    /**
     * 下载完成，点击安装
     */
    private void installApk() {
        File file = new File(Constants.RootApkPath + apkName);

        if (!file.exists()) {
            LogUtils.e("文件" + apkName + "不存在");
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //PendingIntent pendingIntent = PendingIntent.getActivity(UpdateService.this, 0, intent, 0);

        builder.setAutoCancel(true);
        builder.setContentText("点酒下载完成");
        builder.setProgress(100, 100, false);
        //builder.setContentIntent(pendingIntent);//设置pendingIntent后点击通知栏消息，执行安装

        notification = builder.build();

        notificationManager.notify(1, notification);

        stopSelf();

        FileUtils.InstallApk(DownloadService.this, file);
    }

    private Notification.Builder getNotifivationBuilder() {
        if (builder == null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//8.0系统之上
                builder = getTargetApiNotifivationBuilder();
            } else {
                builder = new Notification.Builder(DownloadService.this);
            }
        }

        builder.setOnlyAlertOnce(true);

        return builder;
    }

    @TargetApi(Build.VERSION_CODES.O)
    private Notification.Builder getTargetApiNotifivationBuilder() {
        NotificationChannel channel = new NotificationChannel(String.valueOf(mChannelId), "pugua", NotificationManager.IMPORTANCE_HIGH);

        notificationManager.createNotificationChannel(channel);

        builder = new Notification.Builder(DownloadService.this, String.valueOf(mChannelId));

        //或者
        //builder = new Notification.Builder(context);
        //builder.setChannelId(String.valueOf(channelId)); //创建通知时指定channelId

        return builder;
    }
}
